/**
* ...
* @author Donald Martinez
* @version 0.1
*/

package bdz.common.effects {
	import flash.display.*;
	import bdz.common.utils.BitmapUtils;
	import flash.geom.*;
	import fl.motion.MatrixTransformer;
	import flash.system.Security;
	public dynamic class Reflection extends Sprite {
		private var gradientSprite:Sprite;
		private var bmpCopy:Bitmap;
		private var myTarget:Sprite;
		private var gmatrix:Matrix;
		private var _distance:Number;
		private var _length:Number;
		private var _ratio:Number;
		private var _alpha:Number;
		public function Reflection(targ:Sprite, length:Number, distance:Number = 0, alp:Number = 1, ratio:Number = 255) {
			
			if (targ["reflection"] is Reflection) {
				//targ.removeChild(targ["reflection"]);
				//refresh();
				return;
			}
			Security.allowDomain("*");
			_alpha = alp;
			_ratio = ratio;
			_length = length;
			_distance = distance;
			myTarget = targ;
			
			createReflection();
			targ.addChild(this);
			targ["reflection"] = this;
			
		}
		private function createReflection():void {
			gmatrix = new Matrix();
			gmatrix.createGradientBox(myTarget.width, _length, (90/180)*Math.PI, 0, 0);
			
			createInvertedCopy();
			createGradient();
			y = myTarget.height+_distance;
			gradientSprite.cacheAsBitmap = bmpCopy.cacheAsBitmap = true;
			
			
			bmpCopy.mask = gradientSprite;
		}
		public function refresh():void {
			
			bmpCopy.bitmapData.draw(myTarget);
			
		}
		private function createGradient():void{
			if(!gradientSprite){
				gradientSprite = new Sprite();
			}
			gradientSprite.blendMode = "layer";
			gradientSprite.graphics.lineStyle(1, 0x000000, 0);
			
			gradientSprite.graphics.beginGradientFill(GradientType.LINEAR, [0x000000,0x00ffffff], [_alpha,0], [0,_ratio], gmatrix, SpreadMethod.PAD, InterpolationMethod.RGB, 0);
			gradientSprite.graphics.drawRect(0, 0, bmpCopy.width, bmpCopy.height);
			gradientSprite.graphics.endFill();
			addChild(gradientSprite);
			
		}
		private function createInvertedCopy():void {
			bmpCopy = new Bitmap(new BitmapData(myTarget.width, myTarget.height, true, 0x00ffffff), "auto", true);
			bmpCopy.bitmapData.draw(myTarget);
			
			//= BitmapUtils.capture(myTarget);
			var mat:Matrix = bmpCopy.transform.matrix;
			mat.ty = bmpCopy.transform.matrix.ty+bmpCopy.height;
			MatrixTransformer.setScaleY(mat, -1);
			bmpCopy.transform.matrix = mat;
			addChild(bmpCopy);
		}
		public function skewX(n:Number):void{
			var omat:Matrix = bmpCopy.transform.matrix;
			omat.ty = 0;
			MatrixTransformer.setSkewX(omat, n);
			MatrixTransformer.setScaleY(omat, -1);
			bmpCopy.transform.matrix = omat;
			
		}
	}
	
}